<template>
  <div class="createPost-container">
    <el-form ref="postForm" :model="postForm" :rules="rules" class="form-container">

      <sticky :z-index="10" :class-name="'sub-navbar '+postForm.status">
        <el-button v-loading="loading" style="margin-left: 10px;" type="success" @click="submitForm">
          发布
        </el-button>
      </sticky>

      <div class="createPost-main-container">
        <el-row>
          <el-col :span="24">
            <el-form-item style="margin-bottom: 40px;" prop="title">
              <MDinput v-model="postForm.title" :maxlength="100" name="name" required>
                文章标题
              </MDinput>
            </el-form-item>

            <el-form-item label-width="60px" label="概述:" prop="synopsis" class="postInfo-container-item">
              <el-input
                type="textarea"
                :rows="2"
                placeholder="请输入概述"
                v-model="postForm.synopsis">
              </el-input>
            </el-form-item>

            <div class="postInfo-container">
              <el-row>
                <el-col :span="8">
                  <el-form-item label-width="60px" label="作者:" prop="auther" class="postInfo-container-item">
                    <el-input v-model="postForm.auther" type="input" placeholder="请输入作者" />
                  </el-form-item>
                </el-col>

                <el-col :span="10">
                  <el-form-item label-width="130px" label="所属分类:" prop="cid" class="postInfo-container-item">
                    <el-select v-model.number="postForm.cid" class="filter-item" placeholder="请选择分类" clearable>
                      <el-option v-for="item in cateList" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                  </el-form-item>
                </el-col>

                <el-col :span="6">
                  <el-form-item label-width="90px" prop="sort" label="排序:" class="postInfo-container-item">
                    <el-input v-model.number="postForm.sort" type="number" placeholder="请输入正整数" />
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </el-col>
        </el-row>

        <el-form-item prop="image" style="margin-bottom: 30px;" label="封面图:">
          <Upload v-model="postForm.image" :imgHeight="60" :imgMarginTop="20" />
          <span class="el-upload__tip">只能上传jpg/jpeg/png文件，建议尺寸为500px*300px</span>
        </el-form-item>

        <el-form-item prop="content" style="margin-bottom: 30px;">
          <Tinymce ref="editor" v-model="postForm.content" :height="400" />
        </el-form-item>
      </div>
    </el-form>
  </div>
</template>

<script>
import Tinymce from '@/components/Tinymce'
import Upload from '@/components/Upload/SingleImage'
import MDinput from '@/components/MDinput'
import Sticky from '@/components/Sticky' // 粘性header组件
import { fetchArticle, addArticle, updateArticle } from '@/api/article'
import { articleCateList } from "@/api/article-cate";

const defaultForm = {
  id: undefined,
  status: 1,
  title: '', // 文章题目
  content: '', // 文章内容
  sort: 100,
  auther: '',
  cid: null,
  isBanner: 1,
  image: '', // 文章图片
  isHot: 0,
  adminId: 0,
  synopsis: '',
  hidden: 0,
}

export default {
  name: 'ArticleDetail',
  components: { Tinymce, MDinput, Upload, Sticky },
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      postForm: Object.assign({}, defaultForm),
      loading: false,
      userListOptions: [],
      rules: {
        title: [{ required: true, message: "必须填写标题", trigger: "blur" }],
        synopsis: [{ required: true, message: "必须填写简介", trigger: "blur" }],
        content: [{ required: true, message: "必须输入内容", trigger: "blur" }],
        cid: [{ required: true, message: "必须选择分类", trigger: "blur" }],
        sort: [{ required: true, type: 'number', message: "必填且只能输入数字", trigger: "blur" }]
      },
      tempRoute: {},
      cateList: []
    }
  },
  computed: {
    contentShortLength() {
      return this.postForm.content_short.length
    },
    displayTime: {
      // set and get is useful when the data
      // returned by the back end api is different from the front end
      // back end return => "2013-06-25 06:59:25"
      // front end need timestamp => 1372114765000
      get() {
        return (+new Date(this.postForm.display_time))
      },
      set(val) {
        this.postForm.display_time = new Date(val)
      }
    }
  },
  created() {
    this.getCateList();

    if (this.isEdit) {
      const id = this.$route.params && this.$route.params.id
      this.fetchData(id)
    }

    // Why need to make a copy of this.$route here?
    // Because if you enter this page and quickly switch tag, may be in the execution of the setTagsViewTitle function, this.$route is no longer pointing to the current page
    // https://github.com/PanJiaChen/vue-element-admin/issues/1221
    this.tempRoute = Object.assign({}, this.$route)
  },
  methods: {
    // 获取文章分类
    getCateList() {
      articleCateList({ pageType: "A" }).then(response => {
        let data = response.data;
        for (let i in data) {
          if (data[i].hidden == 0)
          {
            this.cateList.push({ value: data[i].id, label: data[i].title });
          }
        }
      });
    },
    fetchData(id) {
      fetchArticle({id: id}).then(response => {
        this.postForm = response.data

        // set tagsview title
        this.setTagsViewTitle()
        // set page title
        this.setPageTitle()
      }).catch(err => {
        console.log(err)
      })
    },
    setTagsViewTitle() {
      const title = 'Edit Article'
      const route = Object.assign({}, this.tempRoute, { title: `${title}-${this.postForm.id}` })
      this.$store.dispatch('tagsView/updateVisitedView', route)
    },
    setPageTitle() {
      const title = 'Edit Article'
      document.title = `${title} - ${this.postForm.id}`
    },
    submitForm() {
      this.$refs.postForm.validate(valid => {
        // 创建人ID
        this.postForm.adminId = this.$store.getters['user/user_id'];
        if (valid) {
          this.loading = true
          console.log(this.postForm);

          if (this.isEdit)
          {
            // 修改文章
            updateArticle(this.postForm).then(response => {
              if (response.success === true)
              {
                this.$notify({
                  title: '成功',
                  message: '更新文章成功',
                  type: 'success',
                  duration: 2000
                })
              }
              else
              {
                this.$notify({
                  title: '失败',
                  message: response.errorDetail,
                  type: 'error',
                  duration: 2000
                })
              }
            });
          }
          else
          {
            // 添加文章
            addArticle(this.postForm).then(response => {
              if (response.success === true)
              {
                this.$notify({
                  title: '成功',
                  message: '发布文章成功',
                  type: 'success',
                  duration: 2000
                })
              }
              else
              {
                this.$notify({
                  title: '失败',
                  message: response.errorDetail,
                  type: 'error',
                  duration: 2000
                })
              }
            });
          }
          this.loading = false
          this.$router.go(-1);
        } else {
          return false
        }
      })
    }
  }
}
</script>
<style>
.upload-container .image-preview .image-preview-wrapper img {
    width: 100%;
    height: 60% !important;
    margin-top: 20%;
}
</style>
<style lang="scss" scoped>
@import "~@/styles/mixin.scss";

.createPost-container {
  position: relative;

  .createPost-main-container {
    padding: 40px 45px 20px 50px;

    .postInfo-container {
      position: relative;
      @include clearfix;
      margin-bottom: 10px;

      .postInfo-container-item {
        float: left;
      }
    }
  }

  .word-counter {
    width: 40px;
    position: absolute;
    right: 10px;
    top: 0px;
  }
}

.article-textarea ::v-deep {
  textarea {
    padding-right: 40px;
    resize: none;
    border: none;
    border-radius: 0px;
    border-bottom: 1px solid #bfcbd9;
  }
}
</style>
